package craky.keeper.user;

import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import craky.keeper.util.HibernateUtil;

public class UserDAO
{
    public static User login(String name, String password)
    {
        List<User> users = getUsers(Restrictions.eq("name", name));
        User user = null;
        
        if(users.size() > 0 && !(user = users.get(0)).getPassword().equals(password))
        {
            user.setPassword(null);
        }
        
        return user;
    }
    
    public static boolean isFirst()
    {
        return getUsers(Restrictions.eq("purview", User.ADMIN)).isEmpty();
    }
    
    @SuppressWarnings("unchecked")
    public static List<User> getUsers(Criterion...criterions)
    {
        return (List<User>)HibernateUtil.getDatas(User.class, criterions);
    }
    
    public static void addUser(User user)
    {
        HibernateUtil.insert(user);
    }
    
    public static void deleteUser(User user)
    {
        HibernateUtil.delete(user);
    }
    
    public static void updateUser(User user)
    {
        HibernateUtil.update(user);
    }
}